#include "Map.hpp"
#include "Logger.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "DestructibleBox.hpp"
#include "MetalBox.hpp"


Map::Map ():
m_modeles(),
m_backgrounds(),
m_boxes(),
m_background()
{
	sf::Image i;
	i.LoadFromFile("data/maps/cross.png");
	m_modeles["cross"] = i;
	
	i.LoadFromFile("data/images/granite.jpg");
	m_backgrounds["granite"] = i;
}
	
Map::~Map ()
{
}
	
void Map::loadModele(const std::string& modele)
{
	m_boxes.clear(); // reset
	
	if(m_modeles.find(modele) == m_modeles.end())
	{
		LogErr << "Unable to load modele  : " << modele << ". Reason : the modele requested is unknown." << LogEnd;
		return;
	}
	
	srand(static_cast<unsigned int>(time(NULL)));
	// 0 - 100 101 201
	sf::Image image = m_modeles[modele];
	for(unsigned int x = 0; x < image.GetWidth(); ++x)
	{
		for(unsigned int y = 0; y < image.GetHeight(); ++y)
		{
			int pixelValue = image.GetPixel(x,y).r;
			int randValue = rand() % 101;
			bool metal = pixelValue > 100;
			
			if(metal) // = metal box
			{
				pixelValue -= 101;
				if(randValue < pixelValue)
					m_boxes[x*image.GetWidth()+y] = BoxPtr(new MetalBox(*this,x*40,y*40,x*image.GetWidth()+y));
			}
			else // = normal box
			{
				if(randValue < pixelValue)
					m_boxes[x*image.GetWidth()+y] = BoxPtr(new DestructibleBox(*this,x*40,y*40,x*image.GetWidth()+y));
			}
		}
	}
	
	LogInfo << "Generate map from modele : " << modele << " was done with success." << LogEnd;
}
		
std::map<unsigned int,BoxPtr>& Map::boxes()
{
	return m_boxes;
}
		
		
void Map::removeBoxAt(const unsigned int index)
{
	if(m_boxes.find(index) != m_boxes.end())
		m_boxes.erase(index);
}

void Map :: clearBoxes()
{
	m_boxes.clear();
}

void Map::setBackground(const std::string& b)
{
	if(m_backgrounds.find(b) != m_backgrounds.end())
		m_background = m_backgrounds[b];
}

sf::Image& Map::background()
{
	return m_background;
}
